import React, {Component} from 'react';
import moment from 'moment';
import {
  List,
  Card,
  Row,
  Col,
  Radio,
  Input,
  Progress,
  Button,
  Icon,
  Dropdown,
  Menu,
  Modal,
  Avatar,
  Form,
  DatePicker,
  Select,
  Upload,
} from 'antd';
import styles from './list.less';

import {messageNotice as message} from 'common/utils';
import {UPLOAD_URL, OPERATE_URL, MOVE_OPERATE_POSITION} from 'constant/url';
import {
  BANNER,
  NEWS,
  COMMENT,
  TOPIC,
  SUBJECT,
  OPERATEARRAY,
} from 'constant/type';
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const DATE_FORMAT = 'YYYY-MM-DD HH:mm';

const typeToDesc = type => {
  let desc;
  switch (type) {
    case BANNER.type:
      desc = BANNER.desc;
      break;
    case NEWS.type:
      desc = NEWS.desc;
      break;
    case COMMENT.type:
      desc = COMMENT.desc;
      break;
    case TOPIC.type:
      desc = TOPIC.desc;
      break;
    case SUBJECT.type:
      desc = SUBJECT.desc;
      break;
  }
  return desc;
};

const ListContent = ({data: {showImg, img, title, validateDate}}) => (
  <div className={styles.listContent}>
    {showImg ? (
      <div className={styles.listContentItem}>
        <img src={img[0] ? img[0].url : ''} style={{width: 160, height: 90}} />
      </div>
    ) : null}
    <div className={styles.listContentItem}>
      <p
        style={{
          width: 120,
          textOverflow: 'ellipsis',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
        }}>
        {title}
      </p>
    </div>
    <div className={styles.listContentItem}>
      <span>有效期</span>
      <p>{moment(validateDate).format('YYYY-MM-DD HH:mm')}</p>
    </div>
  </div>
);

class CreateDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: this.props.editData.img
        ? JSON.parse(this.props.editData.img)
        : [],
    };
  }
  handleChange = ({fileList}) => {
    if (
      fileList.length > 0 &&
      fileList[0].status == 'done' &&
      fileList[0].response.code == 0
    ) {
      let fileObj = {};
      fileObj.url = fileList[0].response.data.url;
      fileObj.name = fileList[0].name;
      fileObj.uid = 1;
      this.props.uploadFileChange([fileObj]);
    }
    this.setState({fileList});
  };
  _beforeUpload = (file, fileList) => {
    let fileSize = 1024 * 1024;
    if (file.size / fileSize >= 1) {
      const size =
        1024 > fileSize
          ? fileSize + 'B'
          : 1024 * 1024 > fileSize
            ? fileSize / 1024 + 'KB'
            : fileSize / 1024 / 1024 + 'M';
      message.error('图片请保证在' + size + '以内');
      return false;
    }
    return true;
  };
  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
      },
    };
    const {getFieldDecorator} = this.props.form;
    const {isEdit, editData, type, showImg} = this.props,
      {fileList} = this.state;
    return (
      <Form>
        <FormItem {...formItemLayout} label="标题">
          {getFieldDecorator('title', {
            rules: [{required: true, message: '请输入标题'}],
            initialValue: isEdit ? editData.title : '',
          })(<Input />)}
        </FormItem>

        {type == 'banner' ? (
          <FormItem {...formItemLayout} label="副标题">
            {getFieldDecorator('subtitle', {
              rules: [{required: true, message: '请输入副标题'}],
              initialValue: isEdit ? editData.subtitle : '',
            })(<Input />)}
          </FormItem>
        ) : null}

        {showImg ? (
          <FormItem
            {...formItemLayout}
            label={typeToDesc(type)}
            extra=".jpg、.jpeg、.png">
            <Upload
              name="files"
              accept="image/*"
              fileList={fileList}
              beforeUpload={this._beforeUpload}
              onChange={this.handleChange}
              action={UPLOAD_URL}
              listType="picture">
              {fileList.length < 1 ? (
                <Button>
                  <Icon type="upload" /> 上传图片
                </Button>
              ) : null}
            </Upload>
          </FormItem>
        ) : null}

        <FormItem {...formItemLayout} label="有效期">
          {getFieldDecorator('validateDate', {
            rules: [{required: true, message: '请输入有效期'}],
            initialValue: isEdit
              ? moment(editData.validateDate, DATE_FORMAT)
              : null,
          })(<DatePicker showTime={{format: 'HH:mm'}} format={DATE_FORMAT} />)}
        </FormItem>
        {type == 'subject' ? (
          <FormItem {...formItemLayout} label="文章ID">
            {getFieldDecorator('releateArticle', {
              //initialValue: isEdit ? editData.releateArticle : '',
              initialValue: isEdit && editData.releateArticle ? editData.releateArticle.split(",") : [],
            })(
              <Select
                mode="tags"
                placeholder="请输入文章ID"
                style={{width: '100%'}}
                value={[1, 2]}
              />,
            )}
          </FormItem>
        ) : (
          <FormItem {...formItemLayout} label="文章ID">
            {getFieldDecorator('releateArticle', {
              //initialValue: isEdit ? editData.releateArticle : '',
              initialValue: isEdit ? editData.releateArticle : '',
            })(<Input />)}
          </FormItem>
        )}
      </Form>
    );
  }
}

const CreateDialogForm = Form.create()(CreateDialog);

class OperateList extends Component {
  //状态初始化
  constructor(props) {
    super(props);
    this.state = {
      showModal: false,
      radioValue: 1,
      isEdit: false,
      list: [],
      fileList: [],
      editData: {},
      pageNo: 1,
      pageSize: 5,
    };
  }
  //组件生命周期
  componentDidMount() {
    this.getOperateList(this.getQuery());
  }
  //获取运营列表
  getOperateList(query) {
    get(OPERATE_URL, query).then(res => {
      this.setState({
        list: res.list,
      });
    });
  }
  getQuery() {
    let query = {
      type: this.props.type,
      flag: this.state.radioValue,
      pageNo: this.state.pageNo,
      pageSize: this.state.pageSize,
    };
    return query;
  }
  handleClick = (item, moveType) => {
    let {type} = this.props;
    post(MOVE_OPERATE_POSITION, {
      operateId: item.id,
      type,
      moveType,
    }).then(res => {
      message.success('更新成功！');
      this.getOperateList(this.getQuery());
    });
  };
  handleCreateNew = () => {
    this.setState({
      isEdit: false,
      showModal: true,
    });
  };
  handleCancel = () => {
    this.setState({
      isEdit: false,
      showModal: false,
    });
  };
  handleEdit(record) {
    this.setState({
      isEdit: true,
      showModal: true,
      editData: record,
    });
  }
  handleOk = () => {
    const isEdit = this.state.isEdit;
    this.refs.CreateDialogForm.validateFields((err, values) => {
      if (!err) {
        let img =
          this.state.fileList.length > 0
            ? this.state.fileList
            : this.state.editData.img;
        //let img = this.state.fileList || this.state.editData.img;
        const valuesRel = {
          ...values,
          validateDate: values['validateDate'].format('YYYY-MM-DD HH:mm'),
          img: typeof img == 'object' ? JSON.stringify(img) : img,
        };
        if (isEdit) {
          this.modifyOperateInfo(valuesRel);
        } else {
          this.createNew(valuesRel);
        }
      }
    });
  };
  //编辑运营位
  modifyOperateInfo(query) {
    let {type} = this.props,
      operateId = this.state.editData.id;
    if(query.releateArticle && Array.isArray( query.releateArticle)){
        query.releateArticle = query.releateArticle.join(',');
    }
    put(`${OPERATE_URL}/${operateId}`, {type, ...query}).then(res => {
      this.setState({
        showModal: false,
      });
      message.success('更新成功！');
      this.getOperateList(this.getQuery());
    });
  }
  //新建运营位
  createNew(query) {
    let {type} = this.props;
    if(query.releateArticle && Array.isArray( query.releateArticle)){
        query.releateArticle = query.releateArticle.join(',');
    }
    post(OPERATE_URL, {type, ...query}).then(res => {
      this.setState({
        showModal: false,
      });
      message.success('新建成功！');
      this.getOperateList(this.getQuery());
    });
  }
  //删除运营位
  deleteOperate(query) {
    deleteAxios(`${OPERATE_URL}/${query.operateId}`, query).then(res => {
      message.success('删除成功！');
      this.getOperateList(this.getQuery());
    });
  }
  handleDelete(data, type) {
    const me = this;
    Modal.confirm({
      title: '删除',
      content: '是否删除选中？',
      okText: '是',
      cancelText: '否',
      onOk: function() {
        me.deleteOperate({type, operateId: data.id});
      },
    });
  }
  //文件上传变更
  uploadFileChange = fileList => {
    this.setState({fileList});
  };
  //单选框切换
  onRadioChange = e => {
    this.setState(
      {
        radioValue: e.target.value,
        list: [],
      },
      () => {
        this.getOperateList(this.getQuery());
      },
    );
  };
  render() {
    const {showModal, list, radioValue, isEdit, editData} = this.state;

    const {type} = this.props;

    let maxLength = 6,
      showImg = false;

    switch (type) {
      case BANNER.type:
        showImg = true;
        break;
      case NEWS.type:
        showImg = false;
        break;
      case COMMENT.type:
        showImg = false;
        break;
      case TOPIC.type:
        showImg = true;
        break;
      case SUBJECT.type:
        showImg = true;
        break;
      default:
        break;
    }

    //控制排序按钮显示逻辑 radioValue 1/当前使用 0/已过期
    const flag = radioValue == 1 ? true : false;
    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup defaultValue="1" onChange={this.onRadioChange}>
          <RadioButton value="1">当前使用</RadioButton>
          <RadioButton value="0">已过期</RadioButton>
        </RadioGroup>
      </div>
    );
    return (
      <div className={styles.standardList}>
        <Card
          className={styles.listCard}
          bordered={false}
          style={{marginTop: 24}}
          bodyStyle={{padding: '0 32px 40px 32px'}}
          extra={extraContent}>
          {flag ? (
            <Button
              type="dashed"
              style={{width: '100%', marginBottom: 8}}
              onClick={this.handleCreateNew}
              disabled={list.length < maxLength ? false : true}
              icon="plus">
              {' '}
              添加
            </Button>
          ) : (
            ''
          )}
          <List
            size="large"
            rowKey="id"
            dataSource={list}
            renderItem={item => (
              <List.Item
                actions={
                  flag
                    ? [
                        //<a>下线</a>,
                        <a onClick={() => this.handleEdit(item)}>编辑</a>,
                      ]
                    : [<a onClick={() => this.handleDelete(item, type)}>删除</a>]
                }>
                <List.Item.Meta
                  avatar={
                    flag ? (
                      <Avatar
                        style={{backgroundColor: '#1890ff'}}
                        onClick={() => {
                          let type = item.prevId == -1 ? 'down' : 'up';
                          this.handleClick(item, type);
                        }}
                        icon={item.prevId == -1 ? 'down' : 'up'}
                      />
                    ) : (
                      ''
                    )
                  }
                />
                <ListContent
                  data={{
                    showImg,
                    img: item.img ? JSON.parse(item.img) : '',
                    title: item.title,
                    validateDate: item.validateDate,
                  }}
                />
              </List.Item>
            )}
          />
        </Card>
        {showModal ? (
          <Modal
            visible={showModal}
            wrapClassName="vertical-center-modal default-popup"
            onCancel={this.handleCancel}
            onOk={this.handleOk}
            title={`${isEdit ? '编辑' : '新增'}${typeToDesc(type)}`}
            okText="确定"
            cancelText="取消">
            <CreateDialogForm
              type={type}
              showImg={showImg}
              uploadFileChange={this.uploadFileChange}
              ref="CreateDialogForm"
              isEdit={isEdit}
              editData={editData}
            />
          </Modal>
        ) : (
          ''
        )}
      </div>
    );
  }
}

export default OperateList;
